package com.buttonpay.home;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.buttonpay.AppData;
import com.buttonpay.DataHelper;
import com.buttonpay.ImageLoader;
import com.buttonpay.Products;
import com.buttonpay.R;

public class Top_up extends Activity 
{
    /** Called when the activity is first created. */
     
	ListView lvperatorList;
	Button btnBack,btnLogout;
	ArrayList<Products> topUpProducts;
	private DataHelper dh;
	@Override
    public void onCreate(Bundle savedInstanceState) 
    {
		
		super.onCreate(savedInstanceState);
        setContentView(R.layout.top_up_layout);
        
        topUpProducts=AppData.getTopUpProductList();
         
//        for(Products p: AppData.getTopUpProductList())
//        {
//        		topUpProducts.add(p);
//        } 
//        String[] values = new String[] 
//        { 
//          "Vodacom", "Airtel", "Tigo",  "Zantel"
//    	  }; 
//         Integer[] icons = 
//         {
//        	R.drawable.icon_airtel,
//        	R.drawable.icon_vodacom, 
//            R.drawable.icon_zantel,
//            R.drawable.icon_tigo,
//         };
        
        lvperatorList=(ListView)findViewById(R.id.lvOperatorList);
        btnBack=(Button)findViewById(R.id.btnPrevious);
        btnLogout=(Button)findViewById(R.id.btnLogout);
        
        //MyListAdapter adapter = new MyListAdapter(this, values,icons,topUpProducts);
        MyListAdapter adapter = new MyListAdapter(this,topUpProducts);
		lvperatorList.setAdapter(adapter);
		
		btnBack.setOnClickListener(new OnClickListener()
		{
			
			public void onClick(View arg0) 
			{
				// TODO Auto-generated method stub
				finish();
			}
			
		});
		
		btnLogout.setOnClickListener(new OnClickListener()
		{
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new AlertDialog.Builder(Top_up.this)
		        .setTitle( "Exit Application" )
		        .setMessage( "Are you sure you want to Logout?" )
		        .setPositiveButton("YES", new android.content.DialogInterface.OnClickListener() 
		        {
		            public void onClick(DialogInterface arg0, int arg1) 
		            {
		                //do stuff onclick of YES
		            	setResult(2);
		            	finish();
		            }

					public void onClick(View v) 
					{
						// TODO Auto-generated method stub
						
					}
		        })
		        .setNegativeButton("NO",  new android.content.DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface arg0, int arg1)
		            {
		                //do stuff onclick of CANCEL
		            	arg0.dismiss();
		               
		            }

					public void onClick(View v) 
					{
						// TODO Auto-generated method stub
					}
		        }).show();
				  		
			}
		});
		
		lvperatorList.setOnItemClickListener(new OnItemClickListener()
		{

			public void onItemClick(AdapterView<?> arg0, View view, int position,
					long arg3) 
			{
				
				//TextView tvOperatorName=(TextView)view.findViewById(R.id.tvOperatorName);
				Products p=topUpProducts.get(position); 
				TopUpDialog topUpDialog=new TopUpDialog(view.getContext(),p);
				topUpDialog.show();
				 
			}
			
		});
		
    }
 
	protected void onStop() {
	    // TODO Auto-generated method stub
	  
	    super.onStop();
	}
	@Override
	protected void onDestroy() {
	    // TODO Auto-generated method stub
	     
	    super.onDestroy();
	}
	 public static class ViewHolder
	 {
			public TextView tvOperatorName;
			public ImageView ivOperatorIcon; 
			public ImageView ivAddToFavourite;
     }
	
	 class MyListAdapter extends ArrayAdapter<Products> 
	 {
			
			private final Context context;
			/*private final String[] values;
			private final Integer[] icons;*/
			LayoutInflater vi ;
			ImageLoader imageLoader;
			ArrayList<Products> myProducts;
			Products p;
			  
			
//			public MyListAdapter(Context context, String[] values, Integer[] icons, ArrayList<Products> Products)
//			{
			public MyListAdapter(Context context,ArrayList<Products> Products)
			{
				super(context, R.layout.row_lv_operator,Products);
				
				this.imageLoader=new ImageLoader(Top_up.this); 
				this.context = context;
				/*this.values = values;
				this.icons=icons;*/
				this.myProducts=Products;
				System.out.println("Size:"+this.myProducts.size());
				vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//				for(int i=0;i<this.myProducts.size();i++)
//				{	
//					this.myProducts.get(i).setImageURL(""+icons[i]);
//				}
				
			}
 
			public View getView(final int position, View convertView, ViewGroup parent) 
			{
				View v = convertView;
				ViewHolder holder = null;
				
				if (v == null) 
				{
						holder=new ViewHolder();  
						v = vi.inflate(R.layout.row_lv_operator, null); 
						holder.tvOperatorName=(TextView) v.findViewById(R.id.tvOperatorName);
						holder.ivOperatorIcon=(ImageView)v.findViewById(R.id.ivOperatorIcon);
						holder.ivAddToFavourite=(ImageView)v.findViewById(R.id.ivAddToFavourite);
						
						v.setTag(holder);
				}
				else
					 holder=(ViewHolder)v.getTag();
					 p=this.myProducts.get(position);
					 
					System.out.println("==>Product Name:"+p.getProductName());
					System.out.println("==>Product Image URL:"+p.getImageURL());
					
					holder.tvOperatorName.setText(p.getProductDesc());
				
					holder.ivOperatorIcon.setTag(p.getImageURL());
					imageLoader.DisplayImage(p.getImageURL(), Top_up.this, holder.ivOperatorIcon);
					//imageLoader.bind(this, holder.ivOperatorIcon, p.getImageURL());
					
					
					if(isFav(topUpProducts.get(position)))
					{
						holder.ivAddToFavourite.setBackgroundResource(R.drawable.favourite_marked);
						holder.ivAddToFavourite.setTag("marked");
					}
					else
					{
						holder.ivAddToFavourite.setBackgroundResource(R.drawable.favourite_unmarked);
						holder.ivAddToFavourite.setTag("unmarked");	
					}
					
					
					
					holder.ivAddToFavourite.setOnClickListener(new OnClickListener()
					{
						 
						public void onClick(View view) 
						{
							
							if(view.getTag().toString().equalsIgnoreCase("unmarked"))
							{
								view.setTag("marked");
								view.setBackgroundResource(R.drawable.favourite_marked);
								//Toast.makeText(getApplicationContext(), values[position]+" Added in your Favourites!",Toast.LENGTH_SHORT).show();
							 
								addProductToFav(myProducts.get(position));
							  	
							}
							else 
							{
								view.setTag("unmarked");
								view.setBackgroundResource(R.drawable.favourite_unmarked);
								//Toast.makeText(getApplicationContext(), values[position]+" Removed from your Favourite!",Toast.LENGTH_SHORT).show();
								 deleteProductFromFav(myProducts.get(position));
							}
						}

						
					}); 
	 
				 	return v; 
			}//getView

			void addProductToFav(Products p)
			{
			
				try
				{
					 dh=new DataHelper(Top_up.this);
					 dh.insert_topupFav(p.getSystemServiceID(),p.getSystemServiceName(),
							 			p.getProductID(), p.getProductName(),
							 			p.getProductDesc(), 
							 			p.getProductType(),
							 			p.getBatchID(),p.getminValue(),p.getMaxValue(),p.getImageURL());
				}
				catch(Exception e)
				{
					e.printStackTrace();
				}
				finally
				{
					if(dh!=null)
					{
						dh.close();
					}
				}
			}
			protected void deleteProductFromFav(Products p) 
			{
				try
				{
					 dh=new DataHelper(Top_up.this);
					 dh.deleteProdctFromFav(p.getProductID());
				}
				catch(Exception e)
				{
					e.printStackTrace();
				}
				finally
				{
					if(dh!=null)
					{
						dh.close();
					}
				}
				
			}

			private boolean isFav(Products p)
			{
				try
				{
					 dh=new DataHelper(Top_up.this);
					// System.out.println("returning true");
					 return dh.isProductInFav(p.getProductID(),p.getminValue(),p.getMaxValue());
					 
 				
				}
				
				catch(Exception e)
				{
					e.printStackTrace();
					return false;
				}
				finally
				{
					if(dh!=null)
					{
						dh.close();
					}
				}
				
			} 
		} 
}	
    
